<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use EasyWeChat;

class getSellOrderExpressInfos extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:get-sell-order-express-infos';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取卖书订单物流轨迹';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("开始获取...");

        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $orders = DB::table('sell_orders')->where('is_express',1)->whereIn('state',[2,3])->get();
        if(!empty($orders))
        {
            foreach ($orders as $v)
            {
                $result = getOrderTracesByJson($v->shipper_code,$v->express_no,$v->express_order_no);
                $result = json_decode($result,true);

                $traces = !empty($result['Traces']) ? json_encode($result['Traces']) : '';
                $state = isset($result['State']) ? $result['State'] : 0;

                if($v->state == 2 && $state == 0)
                {
                    $time = time() - $v->express_time;

                    if($time > 21600 && $v->express_unget_template_message == 0)
                    {
                        //消息通知
                        $user = DB::table('users')->where('id',$v->user_id)->first();
                        $wechat_user = DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                        if(!empty($wechat_user))
                        {
                            $openid = $wechat_user->openid;

                            $express_time_time = date('Y-m-d H:i',$v->express_time);
                            $first = "快递上门取件状态异常\r"."我们发现你预约的（{$express_time_time}）上门取书快递，现在已超出预约取件时间还没有取件成功。如需更改上门取件时间，请通过顺丰短信上的快递员电话，沟通确认新的取件时间。\r\n";
                            $officialAccount->template_message->send([
                                'touser'        => $openid,
                                'template_id'   => 'w1Rfc2Iw6CjYkpWhm7b4KJJOcwP4adUhyANh2oK4vG0',
                                'url'  => '',
                                'miniprogram' => [
                                    'appid'     => config('wechat.mini_program.default.app_id'),
                                    'path'  => '/pages/sale/order/order-detail/order-detail?id='.$v->id,
                                ],
                                'data' => [
                                    'first'      => $first,
                                    'keyword1'   => '超时未返回取件成功状态',
                                    'keyword2'   => '顺丰速运',
                                    'keyword3'   => $v->express_no."\r\n",
                                    'remark'     => '如超过120小时仍未取件成功，订单将自动关闭。'
                                ],
                            ]);
                        }

                        DB::table('sell_orders')->where('id',$v->id)->update(['express_unget_template_message' => 1]);
                    }

                    if($time > 432000)
                    {
                        //超过5天还没物流轨迹 自动关闭
                        DB::table('sell_orders')->where('id',$v->id)->update(['state' => -2,'is_closed' => 1,'is_overtime' => 1, 'cancel_time' => time()]);
                    }
                }

                if($v->state == 2 && $state > 0)
                {
                    $user = DB::table('users')->where('id',$v->user_id)->first();

                    $sell_orders_num = $user->sell_orders_num+1;
                    DB::table('users')->where('id',$v->user_id)->update(['sell_orders_num'=>$sell_orders_num]);
                    DB::table('sell_orders')->where('id',$v->id)->update(['state' => 3, 'express_get_time' => time()]);
                }


                if($state > 0)
                {
                    DB::table('sell_order_express_infos')->insert([
                        'sell_order_id' => $v->id,
                        'express_no'    => $v->express_no,
                        'state'         => $state,
                        'traces'        => $traces,
                    ]);
                }

            }
        }
        $this->info("获取成功...");
    }
}
